<template>
  <span class="m-spinner">
    <i :disabled="isSubDisabled" @click="onSubtract">-</i>
    <input type="text" :value="currentValue" :disabled="max >= 0 && currentValue >= max" @change="onInputChange">
    <i :disabled="isIncDisabled" @click="onIncrease">+</i>
  </span>
</template>

<script>
  export default {
    props: {
      value: {
        type: [Number, String],
        default: 0
      },
      min: {
        type: [Number],
        default: 0
      },
      max: [Number]
    },
    data() {
      return {
        currentValue: this.value,
        isSubDisabled: false, // 最低的disabled
        isIncDisabled: false // 最高的disabled
      }
    },
    created() {
      if (this.currentValue <= this.min) {
        this.isSubDisabled = true
      }
      if (this.max >= 0 && this.currentValue >= this.max) {
        this.isIncDisabled = true
      }
    },
    methods: {
      onSubtract(ev) {
        if (this.isSubDisabled) return
        this.currentValue--
        this.$emit('input', this.currentValue)
      },
      onIncrease() {
        if (this.isIncDisabled) return
        this.currentValue++
        this.$emit('input', this.currentValue)
      },
      onInputChange(ev) {
        this.currentValue = Number(ev.target.value)
        if (this.currentValue < this.min) {
          this.currentValue = this.min
        }
        if (this.max && this.currentValue > this.max) {
          this.currentValue = this.max
        }
        this.$emit('input', this.currentValue)
      }
    },
    watch: {
      value(newVal, oldVal) {
        this.currentValue = newVal >= this.max ? this.max : (newVal <= this.min ? this.min : Number(newVal))
        this.isSubDisabled = this.currentValue <= this.min
        this.isIncDisabled = (this.max >= 0 && this.currentValue >= this.max)
      }
    }
  }
</script>

<style lang="scss">
  .m-spinner {
    display: inline-block;
    font-size: 0;
    height: .6rem;
    line-height: .6rem;
    text-align: center;
    overflow: hidden;
    i {
      display: inline-block;
      width: .8rem;
      height: 100%;
      background: #f4f4f4;
      font-size: 20px;
      color: #999;
      vertical-align: middle;
      &[disabled] {
        color: #c6c5c5;
        cursor: not-allowed;
      }
    }
    input {
      width: 1.4rem;
      height: 100%;
      margin: 0 .06rem;
      background: #f4f4f4;
      font-size: .2rem;
      text-align: center;
      vertical-align: middle;
    }
  }
</style>